<template>
  <div class="device-monitor">
    <!-- 设备状态概览 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card class="status-card online">
          <div class="status-content">
            <div class="status-icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">{{ deviceStats.online }}</div>
              <div class="status-label">在线设备</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="status-card offline">
          <div class="status-content">
            <div class="status-icon">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">{{ deviceStats.offline }}</div>
              <div class="status-label">离线设备</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="status-card maintenance">
          <div class="status-content">
            <div class="status-icon">
              <el-icon><Tools /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">{{ deviceStats.maintenance }}</div>
              <div class="status-label">维护中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="status-card total">
          <div class="status-content">
            <div class="status-icon">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">{{ deviceStats.total }}</div>
              <div class="status-label">设备总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 设备列表和地图 -->
    <el-row :gutter="20" class="main-content">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>设备实时状态</span>
              <div class="header-actions">
                <el-select v-model="statusFilter" placeholder="状态筛选" size="small" @change="filterDevices">
                  <el-option label="全部" value="" />
                  <el-option label="在线" value="online" />
                  <el-option label="离线" value="offline" />
                  <el-option label="维护中" value="maintenance" />
                </el-select>
                <el-button size="small" @click="refreshDevices">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
          </template>
          
          <el-table :data="filteredDevices" :loading="loading" stripe max-height="600">
            <el-table-column prop="device_id" label="设备ID" width="120" />
            
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" :effect="scope.row.status === 'online' ? 'dark' : 'plain'">
                  <el-icon class="status-icon">
                    <CircleCheck v-if="scope.row.status === 'online'" />
                    <CircleClose v-else-if="scope.row.status === 'offline'" />
                    <Tools v-else />
                  </el-icon>
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="电量" width="120">
              <template #default="scope">
                <div class="battery-info">
                  <el-progress
                    :percentage="scope.row.battery_level || 0"
                    :color="getBatteryColor(scope.row.battery_level)"
                    :stroke-width="8"
                    text-inside
                  />
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="当前用户" width="150">
              <template #default="scope">
                <div v-if="scope.row.current_user" class="user-info">
                  <el-avatar :src="scope.row.current_user.avatar_url" :size="24">
                    {{ scope.row.current_user.nickname?.charAt(0) }}
                  </el-avatar>
                  <span class="user-name">{{ scope.row.current_user.nickname }}</span>
                </div>
                <span v-else class="no-user">无用户</span>
              </template>
            </el-table-column>
            
            <el-table-column label="治疗状态" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.treatment_status" :type="getTreatmentStatusType(scope.row.treatment_status)">
                  {{ getTreatmentStatusText(scope.row.treatment_status) }}
                </el-tag>
                <span v-else class="no-treatment">未治疗</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="last_heartbeat" label="最后心跳" width="160">
              <template #default="scope">
                <div class="heartbeat-info">
                  <span>{{ formatDateTime(scope.row.last_heartbeat) }}</span>
                  <el-tag v-if="scope.row.status === 'online'" type="success" size="small" effect="plain">
                    {{ getHeartbeatDelay(scope.row.last_heartbeat) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewDeviceDetail(scope.row)">
                  <el-icon><View /></el-icon>
                  详情
                </el-button>
                <el-button 
                  size="small" 
                  :type="scope.row.status === 'maintenance' ? 'success' : 'warning'"
                  @click="toggleMaintenance(scope.row)"
                >
                  <el-icon><Tools /></el-icon>
                  {{ scope.row.status === 'maintenance' ? '恢复' : '维护' }}
                </el-button>
                <el-dropdown @command="handleDeviceAction">
                  <el-button size="small" type="info">
                    更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{action: 'logs', device: scope.row}">
                        查看日志
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'remote', device: scope.row}" :disabled="scope.row.status !== 'online'">
                        远程控制
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'firmware', device: scope.row}">
                        固件升级
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card title="实时监控">
          <template #header>
            <span>实时监控</span>
          </template>
          
          <!-- 设备状态分布图 -->
          <div class="monitor-section">
            <h4>设备状态分布</h4>
            <DeviceStatusChart :data="deviceStats" />
          </div>
          
          <!-- 电量分布 -->
          <div class="monitor-section">
            <h4>电量分布</h4>
            <BatteryDistributionChart :data="batteryDistribution" />
          </div>
          
          <!-- 实时活动日志 -->
          <div class="monitor-section">
            <h4>实时活动</h4>
            <div class="activity-log">
              <div v-for="activity in realtimeActivities" :key="activity.id" class="activity-item">
                <div class="activity-time">{{ activity.time }}</div>
                <div class="activity-message">{{ activity.message }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 设备详情对话框 -->
    <DeviceDetailDialog
      v-model="showDeviceDetail"
      :device="selectedDevice"
      @refresh="refreshDevices"
    />
    
    <!-- 远程控制对话框 -->
    <RemoteControlDialog
      v-model="showRemoteControl"
      :device="selectedDevice"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  CircleCheck,
  CircleClose,
  Tools,
  Monitor,
  Refresh,
  View,
  ArrowDown
} from '@element-plus/icons-vue'
import DeviceStatusChart from '@/components/charts/DeviceStatusChart.vue'
import BatteryDistributionChart from '@/components/charts/BatteryDistributionChart.vue'
import DeviceDetailDialog from '@/components/devices/DeviceDetailDialog.vue'
import RemoteControlDialog from '@/components/devices/RemoteControlDialog.vue'
import { getDeviceList, getDeviceStats, setDeviceMaintenance } from '@/api/device'
import { formatDateTime } from '@/utils/format'

// 响应式数据
const devices = ref([])
const loading = ref(false)
const statusFilter = ref('')
const selectedDevice = ref(null)
const showDeviceDetail = ref(false)
const showRemoteControl = ref(false)

const deviceStats = ref({
  online: 0,
  offline: 0,
  maintenance: 0,
  total: 0
})

const batteryDistribution = ref([])
const realtimeActivities = ref([])

// WebSocket连接
let websocket: WebSocket | null = null

// 计算属性
const filteredDevices = computed(() => {
  if (!statusFilter.value) return devices.value
  return devices.value.filter(device => device.status === statusFilter.value)
})

// 方法
const refreshDevices = async () => {
  loading.value = true
  try {
    const [devicesResponse, statsResponse] = await Promise.all([
      getDeviceList(),
      getDeviceStats()
    ])
    
    devices.value = devicesResponse.data.devices
    deviceStats.value = statsResponse.data.status_distribution.reduce((acc, item) => {
      acc[item.status] = item.count
      return acc
    }, { online: 0, offline: 0, maintenance: 0 })
    deviceStats.value.total = devices.value.length
    
    batteryDistribution.value = statsResponse.data.battery_distribution
  } catch (error) {
    ElMessage.error('加载设备数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const filterDevices = () => {
  // 筛选逻辑已在计算属性中处理
}

const viewDeviceDetail = (device) => {
  selectedDevice.value = device
  showDeviceDetail.value = true
}

const toggleMaintenance = async (device) => {
  const newStatus = device.status === 'maintenance' ? 'offline' : 'maintenance'
  const action = newStatus === 'maintenance' ? '设置为维护状态' : '恢复正常状态'
  
  try {
    await ElMessageBox.confirm(
      `确定要将设备 "${device.device_id}" ${action}吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await setDeviceMaintenance(device.device_id, newStatus === 'maintenance')
    ElMessage.success(`设备${action}成功`)
    refreshDevices()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleDeviceAction = ({ action, device }) => {
  selectedDevice.value = device
  
  switch (action) {
    case 'logs':
      // 跳转到设备日志页面
      break
    case 'remote':
      showRemoteControl.value = true
      break
    case 'firmware':
      ElMessage.info('固件升级功能开发中...')
      break
  }
}

// 辅助方法
const getStatusType = (status: string) => {
  const types = {
    online: 'success',
    offline: 'danger',
    maintenance: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中'
  }
  return texts[status] || '未知'
}

const getBatteryColor = (level: number) => {
  if (level > 50) return '#67c23a'
  if (level > 20) return '#e6a23c'
  return '#f56c6c'
}

const getTreatmentStatusType = (status: string) => {
  const types = {
    running: 'success',
    paused: 'warning',
    completed: 'info'
  }
  return types[status] || 'info'
}

const getTreatmentStatusText = (status: string) => {
  const texts = {
    running: '治疗中',
    paused: '已暂停',
    completed: '已完成'
  }
  return texts[status] || '未知'
}

const getHeartbeatDelay = (lastHeartbeat: string) => {
  if (!lastHeartbeat) return '无数据'
  
  const delay = Math.floor((Date.now() - new Date(lastHeartbeat).getTime()) / 1000)
  if (delay < 60) return `${delay}秒前`
  if (delay < 3600) return `${Math.floor(delay / 60)}分钟前`
  return `${Math.floor(delay / 3600)}小时前`
}

// WebSocket实时数据
const initWebSocket = () => {
  const wsUrl = `ws://${window.location.host}/ws/devices`
  websocket = new WebSocket(wsUrl)
  
  websocket.onmessage = (event) => {
    const data = JSON.parse(event.data)
    
    switch (data.type) {
      case 'device_status_update':
        // 更新设备状态
        const deviceIndex = devices.value.findIndex(d => d.device_id === data.device_id)
        if (deviceIndex !== -1) {
          devices.value[deviceIndex] = { ...devices.value[deviceIndex], ...data.data }
        }
        break
        
      case 'device_activity':
        // 添加实时活动
        realtimeActivities.value.unshift({
          id: Date.now(),
          time: new Date().toLocaleTimeString(),
          message: data.message
        })
        // 保持最多20条记录
        if (realtimeActivities.value.length > 20) {
          realtimeActivities.value.pop()
        }
        break
        
      case 'stats_update':
        // 更新统计数据
        deviceStats.value = data.stats
        break
    }
  }
  
  websocket.onerror = (error) => {
    console.error('WebSocket连接错误:', error)
  }
  
  websocket.onclose = () => {
    // 5秒后重连
    setTimeout(initWebSocket, 5000)
  }
}

// 生命周期
onMounted(() => {
  refreshDevices()
  initWebSocket()
  
  // 定时刷新数据
  const interval = setInterval(refreshDevices, 30000) // 30秒刷新一次
  
  onUnmounted(() => {
    clearInterval(interval)
    if (websocket) {
      websocket.close()
    }
  })
})
</script>

<style scoped lang="scss">
.device-monitor {
  padding: 20px;
  
  .overview-cards {
    margin-bottom: 20px;
    
    .status-card {
      .status-content {
        display: flex;
        align-items: center;
        
        .status-icon {
          width: 50px;
          height: 50px;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          
          .el-icon {
            font-size: 20px;
            color: white;
          }
        }
        
        .status-info {
          .status-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
          }
          
          .status-label {
            font-size: 14px;
            color: #909399;
            margin-top: 4px;
          }
        }
      }
      
      &.online .status-icon {
        background: #67c23a;
      }
      
      &.offline .status-icon {
        background: #f56c6c;
      }
      
      &.maintenance .status-icon {
        background: #e6a23c;
      }
      
      &.total .status-icon {
        background: #409eff;
      }
    }
  }
  
  .main-content {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
        align-items: center;
      }
    }
    
    .battery-info {
      width: 100px;
    }
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .user-name {
        font-size: 12px;
      }
    }
    
    .no-user, .no-treatment {
      color: #c0c4cc;
      font-size: 12px;
    }
    
    .heartbeat-info {
      display: flex;
      flex-direction: column;
      gap: 4px;
      
      span {
        font-size: 12px;
      }
    }
    
    .status-icon {
      margin-right: 4px;
    }
  }
  
  .monitor-section {
    margin-bottom: 20px;
    
    h4 {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #303133;
    }
    
    .activity-log {
      max-height: 200px;
      overflow-y: auto;
      
      .activity-item {
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .activity-time {
          font-size: 12px;
          color: #909399;
        }
        
        .activity-message {
          font-size: 13px;
          color: #606266;
          margin-top: 2px;
        }
      }
    }
  }
}
</style>